package commons.ui.workbench;

import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

/**
 * Collection of helper methods
 * 
 * @author Ihor
 */

public class WorkbenchHelper {
    public static IEditorPart openWorkbenchEditor(IWorkbenchWindow window, IEditorInput input, String editorId)
	    throws PartInitException {
	if (window == null) {
	    window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	}
	IWorkbenchPage page = window.getActivePage();
	return page.openEditor(input, editorId);
    }

    public static IEditorPart reopenWorkbenchEditor(IWorkbenchWindow window, IEditorInput input, String editorId)
	    throws PartInitException {
	if (window == null) {
	    window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	}
	IWorkbenchPage workbenchPage = window.getActivePage();
	for (IEditorReference reference : workbenchPage.getEditorReferences()) {
	    if (reference.getId().equals(editorId)) {
		IEditorPart editorPart = (IEditorPart) reference.getPart(true);
		workbenchPage.activate(editorPart);
		return editorPart;
	    }
	}
	return workbenchPage.openEditor(input, editorId);
    }

    public static IWorkbenchPage reopenWorkbenchEditorWithTitle(IWorkbenchWindow window, IEditorInput input, String editorId,
	    String title) throws PartInitException {
	if (window == null) {
	    window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	}
	IWorkbenchPage workbenchPage = window.getActivePage();
	IEditorReference[] references = workbenchPage.getEditorReferences();
	for (IEditorReference reference : references) {
	    if (reference.getId().equals(editorId) && title.equals(reference.getTitle())) {
		workbenchPage.activate(reference.getPart(true));
		return workbenchPage;
	    }
	}
	workbenchPage.openEditor(input, editorId);
	return workbenchPage;
    }
}
